<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    width="500px"
    v-loading="loading"
  >
    <el-form label-width="80px">
      <!-- node-key:树节点唯一标识  show-checkbox:是否显示勾选框
      default-checked-keys:默认勾选的集合 
      default-expanded-keys:默认展开 -->
      <el-tree
        :data="menuList"
        ref="tree"
        show-checkbox
        node-key="id"
        accordion
        :default-checked-keys="menuIds"
        :props="{ children: 'children', label: 'name' }"
      >
      </el-tree>
      <el-form-item align="right">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('formData')"
          >确 定
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ApiGetMenuList } from '@/api/menu'
import { ApiGetRoleMenuIds, ApiPostRoleMenuIds } from '@/api/role'
export default {
  props: {
    dialogVisible: { //弹出隐藏
      type: Boolean,
      default: false
    },
    title: { // 标题
      type: String,
      default: ''
    },
    remotePerForm: Function,
    roleId: null
  },
  data () {
    return {
      menuList: [], //所有菜单
      menuIds: [], // 显示的权限
      loading: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  methods: {
    async getMenuList () { // 获取所有权限列表
      this.loading = true
      const res = await ApiGetMenuList({})
      this.menuList = res.data
      this.loading = false
      this.getMenuIds()
    },
    async submitForm () {
      // 获取所有背选中的菜单id
      const checkList = this.$refs.tree.getCheckedKeys()
      const res = await ApiPostRoleMenuIds(this.roleId, checkList)
      if (res.code === 20000) {
        this.$message({
          message: '保存成功', type: 'success'
        })
        this.handleClose()
      } else {
        this.$message({
          type: 'error', message: "保存失败"
        });
      }
    },
    async getMenuIds () { // 查询拥有的权限
      const { data } = await ApiGetRoleMenuIds(this.roleId)
      this.menuIds = data
    },
    handleClose () {
      this.menuList = []
      this.menuIds = []
      this.remotePerForm()
    }
  },
  watch: {
    dialogVisible (val) {
      if (val) {
        this.getMenuList()
      }
    }
  }
}
</script>

<style>
</style>